package nameless.aistudy.domain.service.user.impl;

import nameless.aistudy.common.exception.BusinessException;
import nameless.aistudy.domain.model.statistics.Statistics;
import nameless.aistudy.domain.service.statistics.StatisticsService;
import nameless.aistudy.domain.service.user.UserCheckInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;

import static nameless.aistudy.common.enumeration.message.MessageEnum.CHECKED_IN_TODAY;
import static nameless.aistudy.common.enumeration.message.MessageEnum.NOT_CHECKED_IN_TODAY;
import static nameless.aistudy.common.enumeration.statistics.StatisticsTypeEnum.CONTINUOUS_CHECKIN_DAYS;

@Service
public class UserCheckInServiceImpl implements UserCheckInService {

    @Autowired
    StatisticsService statisticsService;

    @Override
    public boolean checkIn(int userId) {
        LocalDate today = LocalDate.now();

        // 查询今日统计记录
        Statistics statistics = statisticsService.getUserStatistics(userId, CONTINUOUS_CHECKIN_DAYS.getId(), today);
        if (statistics != null) {
            throw new BusinessException(CHECKED_IN_TODAY.getMessage());
        }

        // 查询昨日统计记录
        LocalDate yesterday = today.plusDays(-1);
        statistics = statisticsService.getUserStatistics(userId, CONTINUOUS_CHECKIN_DAYS.getId(), yesterday);

        BigDecimal daily = new BigDecimal(1);
        BigDecimal overall = statistics != null ?
                statistics.getOverall().add(daily) : daily;

        return statisticsService.setUserStatistics(userId, CONTINUOUS_CHECKIN_DAYS.getId(), today, daily, overall);
    }

    @Override
    public int getContinuousCheckInDays(int userId) {
        LocalDate today = LocalDate.now();
        Statistics statistics = statisticsService.getUserStatistics(userId, CONTINUOUS_CHECKIN_DAYS.getId(), today);
        if (statistics == null) {
            throw new BusinessException(NOT_CHECKED_IN_TODAY.getMessage());
        }

        return statistics.getOverall().intValue();
    }

}
